package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.service.TemperatureAnalysisService;
import com.entrogy.service.UserService;
import com.entrogy.utils.constants.Constants;
import com.entrogy.utils.constants.ErrorEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName TemperatureAnalysisController
 * @Description
 * @Author luoxingjiang
 * @Date 2020-02-28 上午 10:47
 * @Version 1.0
 **/
@RestController
@RequestMapping("/temperatureAnalysis")
@Api(description = "学校体温统计接口")
public class TemperatureAnalysisController {

    @Autowired
    private UserService userService;

    @Autowired
    private TemperatureAnalysisService temperatureAnalysisService;

    @GetMapping(value = "/getSchoolTemperatureInfoOverview")
    @ApiOperation(value = "学校体温统计概览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "selectType", value = "查询的类别，1为老师，2为学生", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "selectDate", value = "查询的日期，格式为yyyy-MM-dd HH:mm:ss", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "normalTemperature", value = "体温预警阈值", dataType = "Double", paramType = "query"),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午（type为学生，该值必填）", dataType = "Integer", paramType = "query"),
    })
    public Msg getSchoolTemperatureInfo(String uid, Integer selectType,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date selectDate,
                                        Double normalTemperature, Integer timeFrameType) {
        normalTemperature = normalTemperature == null ? Constants.NORMAL_TEMPERATURE : normalTemperature;
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null) {
            schoolCode = userService.getSchoolCodeByUserId(uid);
        } else {
            uid = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        TemperatureAnalysisEntity temperatureAnalysis = null;
        if (selectType == 1) {
            // 查询当天该学校教师体温数据
            temperatureAnalysis = temperatureAnalysisService.getSchoolTeacherTemperatureInfoOverview(schoolCode, selectDate, normalTemperature);
        } else if (selectType == 2) {
            // 查询当天该学校学生体温数据
            temperatureAnalysis = temperatureAnalysisService.getSchoolStudentTemperatureInfoOverview(schoolCode, selectDate, normalTemperature, timeFrameType);
        }
        temperatureAnalysis.setCheckTemperature(temperatureAnalysis.getTotalCount() - temperatureAnalysis.getNoCheckTemperature());
        return Msg.success().add("temperatureAnalysis", temperatureAnalysis);
    }


    @GetMapping(value = "/listGradeTemperatureInfoOverview")
    @ApiOperation(value = "年级体温统计概览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "selectDate", value = "查询的日期，格式为yyyy-MM-dd HH:mm:ss", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "normalTemperature", value = "体温预警阈值", dataType = "Double", paramType = "query"),
    })
    public Msg listGradeTemperatureInfo(String uid, Integer timeFrameType,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date selectDate,
                                        Double normalTemperature) {
        normalTemperature = normalTemperature == null ? Constants.NORMAL_TEMPERATURE : normalTemperature;
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        List<TemperatureAnalysisEntity> gradeTemperatureInfoList =
                temperatureAnalysisService.listGradeTemperatureInfoOverview(schoolCode, timeFrameType, selectDate, normalTemperature);
        return Msg.success().add("gradeTemperatureInfoList", gradeTemperatureInfoList);
    }

    @GetMapping(value = "/listClassTemperatureInfoOverview")
    @ApiOperation(value = "班级体温统计概览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "selectDate", value = "查询时间", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "gradeId", value = "查询的年级id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "normalTemperature", value = "体温预警阈值", dataType = "Double", paramType = "query"),
    })
    public Msg listClassTemperatureInfo(String uid, Integer timeFrameType,
                                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date selectDate,
                                        Integer gradeId, Double normalTemperature) {
        normalTemperature = normalTemperature == null ? Constants.NORMAL_TEMPERATURE : normalTemperature;
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        List<TemperatureAnalysisEntity> gradeTemperatureInfoList = temperatureAnalysisService.listClassTemperatureInfoOverview(selectDate, schoolCode, gradeId, timeFrameType, normalTemperature);
        return Msg.success().add("gradeTemperatureInfoList", gradeTemperatureInfoList);
    }

    @GetMapping(value = "/getTemperatureInfo")
    @ApiOperation(value = "得到教师或者学生的体温统计详细数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "selectDate", value = "查询时间（格式为yyyy-MM-dd HH:mm:ss）",
                    dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "查询的类别，1为老师，2为学生", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "gradeId", value = "年级id（type为学生时，该值选填）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "classId", value = "班级id（type为学生时，该值选填）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "normalTemperature", value = "体温预警阈值", dataType = "Double", paramType = "query"),
            @ApiImplicitParam(name = "timeFrameType", value = "查询的时段，1为早上，2为中午，3为下午（type为学生时，该值必填）", dataType = "Integer", paramType = "query"),
    })
    public Msg getTemperatureInfo(String uid, String selectDate, Integer type, Integer gradeId, Integer classId,
                                  Double normalTemperature, Integer timeFrameType) {
        normalTemperature = normalTemperature == null ? Constants.NORMAL_TEMPERATURE : normalTemperature;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Integer schoolCode = userService.getSchoolCodeByUserId(uid);
        if (schoolCode == null){
            return Msg.fail(ErrorEnum.E_90012, ErrorEnum.E_90012.getErrorMsg());
        }
        // TODO 此处需要查询未测人员名单
        List<TeacherTemperatureInfoEntity> teacherNormalTemperatureInfoList = new ArrayList<>();    // 教师体温正常人员名单
        List<TeacherTemperatureInfoEntity> teacherAbnormalTemperatureInfoList = new ArrayList<>();    // 教师体温异常人员名单
        List<StudentTemperatureInfoEntity> studentNormalTemperatureInfoList = new ArrayList<>();   // 学生体温正常人员名单
        List<StudentTemperatureInfoEntity> studentAbnormalTemperatureInfoList = new ArrayList<>();   // 学生体温异常人员名单
        switch (type) {
            case 1:
                // 得到查询的时间范围
                LocalDateTime selectStartDate = LocalDateTime.parse(selectDate, df);
                LocalDateTime selectEndDate = selectStartDate.plusHours(24);
                // 查询教师体温正常和不正常的人员以及体温信息
                teacherNormalTemperatureInfoList = temperatureAnalysisService.listTeacherTemp(schoolCode, normalTemperature, true, selectStartDate, selectEndDate);
                teacherAbnormalTemperatureInfoList = temperatureAnalysisService.listTeacherTemp(schoolCode, normalTemperature, false, selectStartDate, selectEndDate);
                break;
            case 2:
                studentNormalTemperatureInfoList = temperatureAnalysisService.listStudentTemp(schoolCode, normalTemperature, true, gradeId, classId, timeFrameType, selectDate);
                studentAbnormalTemperatureInfoList = temperatureAnalysisService.listStudentTemp(schoolCode, normalTemperature, false, gradeId, classId, timeFrameType, selectDate);
                break;
        }
        return Msg.success().add("temperatureNormalPersonList", type == 1 ? teacherNormalTemperatureInfoList : studentNormalTemperatureInfoList)
                .add("temperatureAbnormalPersonList", type == 1 ? teacherAbnormalTemperatureInfoList : studentAbnormalTemperatureInfoList);
    }

//    @GetMapping(value = "/getTemperatureInfo")
//    @ApiOperation(value = "得到教师或者学生的体温统计数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
//            @ApiImplicitParam(name = "date", value = "查询时间", dataType = "String", paramType = "query", required = true),
//            @ApiImplicitParam(name = "type", value = "查询的类别，1为老师，2为学生", dataType = "Integer", paramType = "query", required = true),
//    })
//    public Msg getTemperatureInfo(String uid, String date, Integer type) {
//        final CountDownLatch latch = new CountDownLatch(1);
//        CompletableFuture<Msg> future = CompletableFuture.supplyAsync(() -> {
//            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 得到查询的时间范围
//            LocalDateTime selectStartDate = LocalDateTime.parse(date, df);
//            // 数据库中存储的是秒的时间戳
////            Long startTime = selectStartDate.toInstant(ZoneOffset.of("+8")).getEpochSecond();
//            LocalDateTime selectEndDate = selectStartDate.plusHours(24);
////            Long endTime = selectEndDate.toInstant(ZoneOffset.of("+8")).getEpochSecond();
//            Integer schoolCode = userService.getSchoolCodeByUserId(uid);
//            List<TeacherTemperatureInfoEntity> teacherNormalTemperatureInfoList = new ArrayList<>();    // 教师体温正常人员名单
//            List<TeacherTemperatureInfoEntity> teacherAbnormalTemperatureInfoList = new ArrayList<>();    // 教师体温异常人员名单
//            List<StudentTemperatureInfoEntity> studentNormalTemperatureInfoList = new ArrayList<>();   // 学生体温正常人员名单
//            List<StudentTemperatureInfoEntity> studentAbnormalTemperatureInfoList = new ArrayList<>();   // 学生体温异常人员名单
//            int totalCount = 0;
//            int temperatureNormalCount = 0;
//            int temperatureAbnormalCount = 0;
//            Double normalTemperature = Constants.NORMAL_TEMPERATURE;
//            switch (type) {
//                case 1:
//                    // 查询教师体温正常和不正常的人员以及体温信息
//                    teacherNormalTemperatureInfoList = temperatureAnalysisService.listTeacherTemp(schoolCode, normalTemperature, true, selectStartDate, selectEndDate);
//                    teacherAbnormalTemperatureInfoList = temperatureAnalysisService.listTeacherTemp(schoolCode, normalTemperature, false, selectStartDate, selectEndDate);
//                    totalCount = userService.countSchoolTeacher(schoolCode, null, null, null, null);
//                    temperatureNormalCount = teacherNormalTemperatureInfoList.size();
//                    temperatureAbnormalCount = teacherAbnormalTemperatureInfoList.size();
//                    break;
//                case 2:
//                    studentNormalTemperatureInfoList = temperatureAnalysisService.listStudentTemp(schoolCode, normalTemperature, true, selectStartDate, selectEndDate);
//                    studentAbnormalTemperatureInfoList = temperatureAnalysisService.listStudentTemp(schoolCode, normalTemperature, false, selectStartDate, selectEndDate);
//                    totalCount = studentService.countStudent(schoolCode, null, null, null);
//                    temperatureNormalCount = studentNormalTemperatureInfoList.size();
//                    temperatureAbnormalCount = studentAbnormalTemperatureInfoList.size();
//                    break;
//            }
//            int checkTemperature = temperatureNormalCount + temperatureAbnormalCount;
//            int noCheckTemperature = totalCount - temperatureNormalCount - temperatureAbnormalCount;
//            TemperatureAnalysisEntity temperatureAnalysisInfo = new TemperatureAnalysisEntity();
//            temperatureAnalysisInfo.setCheckTemperature(checkTemperature).setNoCheckTemperature(noCheckTemperature)
//                    .setTemperatureAbnormalCount(temperatureAbnormalCount).setTemperatureNormalCount(temperatureNormalCount)
//                    .setTotalCount(totalCount);
//            latch.countDown();
//            return Msg.success().add("temperatureAnalysisInfo", temperatureAnalysisInfo)
//                    .add("temperatureNormalPersonList", type == 1 ? teacherNormalTemperatureInfoList : studentNormalTemperatureInfoList)
//                    .add("temperatureAbnormalPersonList", type == 1 ? teacherAbnormalTemperatureInfoList : studentAbnormalTemperatureInfoList);
//        });
//        try {
//            latch.await();
//            return future.get();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//
//        }
//        return null;
//    }


    @GetMapping(value = "/listChildTempInfo")
    @ApiOperation(value = "得到自己孩子们的体温统计数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "用户id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "date", value = "查询时间", dataType = "String", paramType = "query", required = true),
    })
    public Msg listChildTempInfo(String uid, String date, Integer studentId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 得到查询的时间范围
        LocalDateTime selectStartDate;
        try {
            selectStartDate = LocalDateTime.parse(date, df);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail(ErrorEnum.E_90013, ErrorEnum.E_90013.getErrorMsg());
        }
        // 数据库中存储的是秒的时间戳
//        Long startTime = selectStartDate.toInstant(ZoneOffset.of("+8")).getEpochSecond();
        LocalDateTime selectEndDate = selectStartDate.plusHours(24);
//        Long endTime = selectEndDate.toInstant(ZoneOffset.of("+8")).getEpochSecond();
        List<StudentTemperatureInfoEntity> studentList = temperatureAnalysisService.listChildTempInfo(uid, selectStartDate, selectEndDate, studentId);
        // 统计学生的体温概览
        for (StudentTemperatureInfoEntity student : studentList) {
            Integer temperatureNormalCount = 0;
            Integer temperatureAbnormalCount = 0;
            List<TemperatureInfoEntity> temperatureList = student.getTemperatureList();
            for (TemperatureInfoEntity temperatureInfo : temperatureList) {
                if (temperatureInfo.getTemperature() >= Constants.NORMAL_TEMPERATURE) {
                    temperatureAbnormalCount++;
                } else {
                    temperatureNormalCount++;
                }
            }
            student.setCheckCount(temperatureList.size()).setTemperatureNormalCount(temperatureNormalCount).setTemperatureAbnormalCount(temperatureAbnormalCount);
        }
        return Msg.success().add("studentList", studentList);
    }


}
